package org.axeidls.api;

import java.util.HashSet;
import java.util.Set;

import org.axe.annotation.ioc.Autowired;
import org.axe.annotation.ioc.Controller;
import org.axe.annotation.ioc.Value;
import org.axe.annotation.mvc.Request;
import org.axe.annotation.mvc.RequestParam;
import org.axe.constant.RequestMethod;
import org.axe.exception.RestException;
import org.axe.util.CollectionUtil;
import org.axeidls.component.DataFileComponent;
import org.axeidls.constant.CleanDataTimeMode;
import org.axeidls.vo.CleanDataResult;

@Controller(name = "工具接口")
public class UtilApi {
	
	@Value("${data.file-path}")
	private String dataFilePath;
	
	@Autowired
	private Api api;
	@Autowired
	private DataFileComponent dfc;
	
	public UtilApi() {}
	
	@Request(path = "clean_data_by_device",method = RequestMethod.DELETE,name = "根据设备清理数据",desc = "所有设备根据指定保留有效期，清理掉过早数据")
	public CleanDataResult clean_data_by_device(
			@RequestParam(name = "devicePathAry",required = true,desc = "设备路径数组，一般是：系统/设备id，*表示所有设备")String[] devicePathAry,
			@RequestParam(name = "cleanDataTimeMode",required = true,desc = "清理模式")CleanDataTimeMode cleanDataTimeMode,
			@RequestParam(name = "keepDataNumber",required = true,desc = "保留时长，配合清理模式，>=0，0表示全部清除但必须在停止接收新数据后")Integer keepDataNumber
			){
		if(devicePathAry.length == 0) {
			throw new RestException("参数devicePathAry必填");
		}
		if(keepDataNumber<0) {
			throw new RestException("参数keepNumber错误，必须>=0");
		}
		if(keepDataNumber == 0) {//清除全部数据
			if(api.get_add_flag() == true) {
				throw new RestException("keepNumber=0表示全部清除，系统仍在接收新数据，请先停止接收新数据");
			}
			
			int dataSize = api.get_add_data_list_size();
			if(dataSize > 0) {
				throw new RestException("新数据队列尚未保存结束，剩余：{}条",dataSize);
			}
			
			int ioSize = dfc.getIoSize();
			if(ioSize > 0) {
				throw new RestException("数据未完全同步到磁盘，剩余io未关闭：{}个",ioSize);
			}
		}
		
		Set<String> cleanDevicePathSet = new HashSet<>();
		for(String devicePath:devicePathAry) {
			cleanDevicePathSet.add(devicePath);
			if(devicePath.equals("*")) {
				//*表示全部要删除
				cleanDevicePathSet.clear();
				break;
			}
		}
		if(CollectionUtil.isEmpty(cleanDevicePathSet)) {
			return dfc.cleanDataAllDevicePath(cleanDataTimeMode, keepDataNumber);
		}else {
			return dfc.cleanDataByDevicePath(cleanDevicePathSet, cleanDataTimeMode, keepDataNumber);
		}
	}
	
}
